/**
 * 
 */
package com.axxc.jpa.service.impl;

import java.util.List;

import javax.transaction.Transactional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import com.axxc.jpa.entity.StudentEntity;
import com.axxc.jpa.repository.IStudentRepository;
import com.axxc.jpa.service.IStudentService;

/**
 * @ClassName: IStudentServiceImpl
 * @Description: TODO(这里用一句话描述这个类的作用)
 * @author 熊小川
 * @date 2018年4月9日 下午10:18:06
 */
@Service
@Transactional
public class StudentServiceImpl implements IStudentService {

	@Autowired
	private IStudentRepository studentRepository;

	@Override
	public List<StudentEntity> findByNameStartingWith(String name) {
		return studentRepository.findByNameStartingWith(name);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.axxc.jpa.service.IStudentService#
	 * readByAgeGreaterThanAndNameStartingWith(java.lang.Integer,
	 * java.lang.String)
	 */
	@Override
	public List<StudentEntity> readByAgeGreaterThanAndNameStartingWith(Integer age, String name) {
		return studentRepository.readByAgeGreaterThanAndNameStartingWith(age, name);
	}

	@Override
	public StudentEntity saveStudent(StudentEntity student) {

		return studentRepository.save(student);
	}

	@Override
	@Cacheable(key = "#p0", cacheNames = "stuCache")//实现了单个ID缓存
	public StudentEntity getStudentById(Long id) {
		System.out.println("缓存不存在,查询数据库.ID为" + id);
		return studentRepository.findOne(id);
	}

	@Override
	public void deleteById(Long id) {
		StudentEntity existStudent = studentRepository.findOne(id);
		if (existStudent != null) {
			studentRepository.delete(existStudent);
		}

	}

	@Override
	public StudentEntity updateStudent(Long id, StudentEntity student) {
		boolean exists = studentRepository.exists(id);
		if (exists) {
			StudentEntity saveAndFlushStudent = studentRepository.saveAndFlush(student);
			return saveAndFlushStudent;
		} else {
			return student;
		}
	}

	@Override
	@Cacheable(value = "stuCache")//实现了缓存,但没有实现根据去查时,再这个缓存里面去获取
	public List<StudentEntity> listAllStudent() {
		System.out.println("查询数据库");
		return studentRepository.findAll();

	}

}
